// pages/share/add/index.js
const app = getApp();
import {
  circledynamicAdd,
  imgUpdate,
  circledynamicclass,
  readArticle
} from '../../../utils/http';
// 图片压缩组件
import ImgCompress from '../../../library/wx-image-compress/img-compress.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    v: app.globalData.v, //版本
    // 上传图片
    fileList: [],

    // tab切换
    tabIndex: 0,

    focus: true,

    // 类型索引
    typeIndex: null,

    dialogShow: false,
    buttons: [{text: '取消'}, {text: '确定'}],
    urlStr: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.imgCompress = new ImgCompress(this, 1000, 1000);
    if (options.type) {
      this.setData({
        tabIndex: options.type
      })

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      theme: app.cSwitch(), //主题色
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.theme.tabbarColor,
    })
    if (this.data.tabIndex == 0 && !this.data.classList) {
      circledynamicclass().then(r => {
        console.log(r)
        if (r.code == 0) {
          this.setData({
            classList: r.data
          })
        }
      })
    }
  },
  changeTab(e) {
    this.setData({
      tabIndex: e.mark.index,
      focus: true
    })
  },

  // 打开文章分类弹窗
  openTypePop() {
    this.setData({
      TypePop: true
    })
  },

  // 关闭文章分类弹窗
  closeTypePop() {
    this.setData({
      TypePop: false
    })
  },
  // 确认文章分类弹窗
  TypePopConfirm(event) {

    let {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      // 类型索引
      typeIndex: index,
      dynamicClass: value.id,
      dynamicClassName: '文章分类：' + value.name,
      TypePop: false
    })
  },


  // 图片尺寸超出提示
  // onOversize(file) {
  //   wx.showToast({
  //     title: '上传图片超过限制，建议上传500kb以下图片',
  //     icon: 'none'
  //   })
  // },
  //上传组件-删除图片
  delSlideImg(e) {
    var f_index = e.detail.index;
    var imageData = this.data.fileList;
    imageData.splice(f_index, 1);
    this.setData({
      fileList: imageData
    })
  },

  //上传组件-图片上传
  async afterRead(e) {
    //上传组件名称
    var _this = this;
    const {
      file
    } = e.detail;
    console.log(file)
    for (var i of file) {
      //图片大于200k开启压缩
      if (i.size > 200 * 1024) {
        /* 
         * imgPath：图片路径
         * aspectRatio：图片宽高压缩比，0～1，默认0.5
         * quality：图片质量，0～1，默认0.5
         */
        await _this.imgCompress.compress(i.url, 1, 0.94).then(res => {
          console.log('压缩成功', res);
          _this.lbDoPostImg(res.compress.path);
        }).catch(e => {
          console.log('图片压缩失败', e);
          _this.lbDoPostImg(i.url);
        })
      } else {
        await _this.lbDoPostImg(i.url);
      }
      // _this.lbDoPostImg(i.url);
    }
  },
  lbDoPostImg(f_path) {
    var _this = this;
    imgUpdate({
      path: f_path
    }).then(res => {
      var res = JSON.parse(res);
      var data = res.data;
      //商品列表图[单图保存json格式，多图保存数组json格式]
      let arr = _this.data.fileList;
      arr.push({
        url: data.kpath
      })
      _this.setData({
        fileList: arr
      })
    })
  },

  openDialog() {
    this.setData({
      dialogShow: true
    })
  },

  tapDialogButton(e) { //剪贴板数据处理
    const _this = this
    console.log(e)
    if (e.detail.item.text == '取消') {
      this.setData({
        dialogShow: false
      })
    } else {
      readArticle({url: this.data.urlStr}).then(res => {
        console.log(res)
        let myEditor = this.selectComponent('#myEditor')
        let str = res.data.content.replace(/data-src/g, "src")
        myEditor.inputValue(str)
        // myEditor.inputValue('<p><img src="https://mmbiz.qpic.cn/mmbiz_jpg/RQ6ZfELahicWmvpCLkV0qsicxNmSOvBZQSBxArksHchxZJ6FVhEyDMGpGCokUuqyDoxl7hpN1pahuickl9u5FYOaA/640?wx_fmt=jpeg" width="100%"></p>')
        // console.log(res.data.content)
        _this.setData({
          content: str,
          // content: '<p><img src="https://mmbiz.qpic.cn/mmbiz_jpg/RQ6ZfELahicWmvpCLkV0qsicxNmSOvBZQSBxArksHchxZJ6FVhEyDMGpGCokUuqyDoxl7hpN1pahuickl9u5FYOaA/640?wx_fmt=jpeg" width="100%"></p>',
          dialogShow: false,
          urlStr: '',
          title: res.data.title
        })
      })
    }
  },


  fabu() {
    let t = this;
    wx.showLoading({
      title: '加载中…',
      mask: true
    })
    if (!t.data.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
      return false;
    }
    if (!t.data.content) {
      wx.showToast({
        title: '请输入分享的内容',
        icon: 'none'
      })
      return false;
    }
    let pic = [];
    if (t.data.fileList.length) {
      t.data.fileList.forEach(i => {
        pic.push(i.url)
      })
    }
    let _data;
    _data = {
      title: t.data.title,
      content: t.data.content,
      type: t.data.tabIndex == 0 ? 1 : 2
    }
    if (t.data.tabIndex == 0) {
      _data.dynamicClass = t.data.dynamicClass;
    }

    circledynamicAdd(_data).then(r => {
      if (r.code == 0) {
        wx.showToast({
          title: '发布成功',
          mask: true
        })
        setTimeout(() => {
          let pages = getCurrentPages();
          let beforePage = pages[pages.length - 2]; // 前一个页面
          wx.navigateBack({
            delta: 1,
            success: function (e) {
              // console.log(pages)
              // console.log(beforePage)
              if (beforePage == undefined || beforePage == null) return;
              beforePage.init();
            }
          })
        }, 1000)
      }
    })

  },

  editorChange(e) {
    console.log(e.detail.params.html)
    this.setData({
      content: e.detail.params.html
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.share();
  }
})